;
(function (window, angular) {
	'use strict';
	angular.module("Controller.BasicData.Printer", [])
		.controller("PrinterCtrl", ["$scope", "$state", "ybHttp", "ybWidget", "MESG_TYPE", "$timeout", "UserContextService", "$q", function ($scope, $state, ybHttp, ybWidget, MESG_TYPE, $timeout, UserContextService, $q) {
			$scope.billPrinterList = [];
			$scope.selectPrinter = { billPIndex: '', codePIndex: '' };

			/*  获取打印机列表*/
			function CreatePrinterList() {
				var deferred = $q.defer();
				var lodop = UserContextService.GetLodop();
				if (lodop) {
					var iPrinterCount = lodop.GET_PRINTER_COUNT();
					for (var i = 0; i < iPrinterCount; i++) {
						$scope.billPrinterList.push({
							idx: i,
							name: lodop.GET_PRINTER_NAME(i)
						});
					}
					deferred.resolve($scope.billPrinterList.find(bp=>bp.name==lodop.GET_PRINTER_NAME(-1)).idx);
				}

				return deferred.promise;
			}

			//保存打印机
			$scope.savePrinter = function () {
				var param = [
					{
						PrinterIdx: $scope.selectPrinter.billPIndex,
					},
					{
						PrinterIdx: $scope.selectPrinter.codePIndex,
					}
				];

				localStorage.setItem("yb.printerSettingList", JSON.stringify(param));
				ybWidget.ShowMessage("保存成功", MESG_TYPE.Success);

				/* ybHttp.Post("device", "/printerConfig/save", { printerJson: JSON.stringify(param) }).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					ybWidget.ShowMessage("保存成功", MESG_TYPE.Success);
				}) */
			};

			function initData() {
				$timeout(function () {
					CreatePrinterList().then((defaultPrinter) => {
						/* ybHttp.Get("device", "/printerConfig/view").then(function (resp) {
							let getSavedPrinter = true;
							if (resp.code !== 0) {
								ybWidget.ShowMessage(resp, MESG_TYPE.Error);
								getSavedPrinter = false;
							}
							if (!resp.value) {
								getSavedPrinter = false;
							}
							if (!getSavedPrinter) {
								$scope.selectPrinter.billPIndex = $scope.selectPrinter.codePIndex = defaultPrinter;
								return;
							}

							const savedPrinters = JSON.parse(resp.value.printerJson);
							$scope.selectPrinter = {
								billPIndex: savedPrinters[0].PrinterIdx,
								codePIndex: savedPrinters[1].PrinterIdx
							};
						}) */

						const savedPrinters = JSON.parse(localStorage.getItem("yb.printerSettingList")||'[]');
						if (savedPrinters.length !=2 ) return;
						$scope.selectPrinter = {
							billPIndex: savedPrinters[0].PrinterIdx,
							codePIndex: savedPrinters[1].PrinterIdx
						};
					})
				}, 0);
			}

			if (window.document.readyState === "complete") {
				initData();
			} else {
				window.addEventListener("load", initData, true);
			}
		}])

})(window, window.angular);